<!--
原料\线缆出库.
包材不是该页面.
-->
<template>
	<a-modal :title="title" :width="1600" :visible="visible" :confirmLoading="confirmLoading" @ok="handleSubmit"
		@cancel="handleCancel">

		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">

						<a-col :md="6" :sm="24" v-if="false">
							<a-form-item label="订单ID">
								<a-input v-model="queryParam.orderId" placeholder="请输入订单ID" />
							</a-form-item>
						</a-col>
						<a-col :md="8" :sm="24">
							<a-form-item label="物料名称">
								<a-input placeholder="请输入物料名称" v-model="queryParam.materialName" />
							</a-form-item>
						</a-col>
						<a-col :md="8" :sm="24">
							<a-form-item label="物料编号">
								<a-input placeholder="请输入物料编号" v-model="queryParam.materialCode" />
							</a-form-item>
						</a-col>
						<a-col :md="8" :sm="24">
							<a-form-item label="领用方">
								<a-select placeholder="全部" v-model="queryParam.classGroupId">
									<a-select-option :values="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
										{{ item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :md="10" :sm="24">
							<a-form-item label="BOM筛选">
								<a-select placeholder="全部" show-search @search="handleSearch" :default-active-first-option="false"
									:show-arrow="false" :filter-option="false" :not-found-content="fetching ? undefined : null"
									@change="handleChange" :value="queryParam.bomName">
									<a-spin v-if="fetching" slot="notFoundContent" size="small" />
									<a-select-option :key="item" v-for="(item, index) in bomData">
										{{ item }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :md="4" :sm="2">
							<a-button type="primary" @click="table.refresh(true)">查询</a-button>
							<a-button
								@click="() => { queryParam.materialCode = null; queryParam.materialName = null; queryParam.classGroupId = null;queryParam.bomName = null; table.refresh(true) }">重置</a-button>
						</a-col>
						<!-- <a-col :md="2" :sm="2" style="float: right;margin-top: 10px;">
							<a-button type="danger" :loading="dwnLoading" @click="handleExport">导出</a-button>
						</a-col> -->
					</a-row>
				</a-form>
			</div>

			<s-table ref="table" size="default" :columns="columns" :data="loadData" :alert="true" :showPagination="false">

				<template slot="materialModelNumber" slot-scope="text, record">
					{{ record.material ? record.material.materialModelNumber : '' }}
				</template>

				<!-- <span slot="image" slot-scope="text">
					<image-preview :images="text" />
				</span> -->
				<span slot="image" slot-scope="text,record">
					<image-preview1 :images="text" :imageUrl="record.material.imageUrl" />
				</span>
				<span slot="classGroupId" slot-scope="text,record">
					<!-- {{record}} -->
					<a-select placeholder="全部" style="width: 100%;" v-model="record.classGroupId">
						<a-select-option :values="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
							{{ item.name }}
						</a-select-option>
					</a-select>
				</span>

				<template slot="completedNumber" slot-scope="text, record">
					<span>
						<span>{{ record.completedNumber }}</span>
						(
						<span class="text-success">正常{{
							record.completedNumber - record.extraNumber
						}}</span>
						<span>，</span>
						<span class="text-danger">额外{{
							record.extraNumber
						}}</span>
						)
					</span>
				</template>
				<template slot="customNormalNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.customNormalNumber" :min="0"
						:max="record.number - (record.completedNumber - record.extraNumber)" style="width: 67px;"
						:disabled="record.completedNumber - record.extraNumber >= record.number" />
				</template>

				<template slot="customExtraNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.customExtraNumber" :min="0" style="width: 67px;"
						:disabled="record.completedNumber - record.extraNumber < record.number" />
				</template>

			</s-table>

		</a-card>
	</a-modal>
</template>

<script lang="ts">
import { Component, Vue, Ref, Prop } from "vue-property-decorator";
import { STable } from '@/components'
import { page } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage.js'
import { addOutOrderForProductionOrder } from '@/api/modular/main/emsorder/emsOrderManage'
import { MATERIAL_TYPE_ENUM } from '@/utils/util'
import { page as bompage, } from '@/api/modular/main/emsbom/emsBomManage'
import { page as teamPage } from '@/api/modular/main/classGroup/classGroup'

@Component({
	components: {
		STable,
	},
})

export default class OrderByWaitOutStoreAddForm extends Vue {
	@Ref() readonly table!: any
	@Prop({ default: false }) readonly: boolean
	@Prop({ default: MATERIAL_TYPE_ENUM.material.id }) materialType: string | number


	title = null
	advanced = false // 高级搜索 展开/关闭
	queryParam = {
		orderId: '',
		materialType: '',
		pageSize: undefined,
		materialCode: null,
		materialName: null,
		classGroupId: undefined,
		bomName: "",
	}  // 查询参数
	viewState = ''
	viewStateEnum = {
		materialOut: 'materialOut',
		packingOut: 'packingOut',
	}
	teamList = []
	bomData = []
	fetching = false
	created() {
		console.log('111')
		this.getTeamList();
	}

	columns = [
		{
			align: 'center',
			title: '物料',
			dataIndex: 'materialName'
		},
		{
			align: 'center',
			title: '规格',
			dataIndex: 'materialModelNumber',
			scopedSlots: { customRender: 'materialModelNumber' }
		},
		{
			align: 'center',
			title: '图片',
			dataIndex: 'image',
			scopedSlots: { customRender: 'image' }
		},
		{
			align: 'center',
			title: '物料编码',
			dataIndex: 'materialCode'
		},
		{
			align: 'center',
			title: '产品',
			dataIndex: 'productName',
		},
		{
			align: 'center',
			title: '产品规格',
			dataIndex: 'material.materialModelNumber',
		},
		{
			align: 'center',
			title: '序列号',
			dataIndex: 'productRecord.extend1',
		},
		{
			align: 'center',
			title: '单个数量',
			// dataIndex: 'number',
			customRender: (text, record, index) => record.number % record.productRecord.number == 0 ? record.number / record.productRecord.number :
				(record.number / record.productRecord.number).toFixed(2),
		},
		{
			align: 'center',
			title: 'BOM',
			dataIndex: 'bomName',
			customRender: (text, record, index) => record.bomName || '/',
		},
		{
			align: 'center',
			title: '总数量',
			dataIndex: 'number'
		},
		{
			align: 'center',
			title: '已出库数量',
			dataIndex: 'completedNumber',
			scopedSlots: { customRender: 'completedNumber' }

		},
		{
			// align: 'center',
			title: '领用方',
			width: 150,
			dataIndex: 'material.classGroupId',
			scopedSlots: { customRender: 'classGroupId' }

		},
		{
			align: 'center',
			title: '正常出库数量',
			scopedSlots: { customRender: 'customNormalNumber' }
		},
		{
			align: 'center',
			title: '额外出库数量',
			scopedSlots: { customRender: 'customExtraNumber' }
		}
	]


	visible = false
	confirmLoading = false
	emsOrder = null
	dwnLoading = false

	// 加载数据方法 必须为 Promise 对象
	loadData(parameter) {
		this.queryParam.orderId = this.emsOrder.orderId
		this.queryParam.materialType = this.materialType as string
		this.queryParam.pageSize = -1
		return page(Object.assign(parameter, this.queryParam)).then((res) => {
			res.data.rows.forEach(value => {
				value.customNormalNumber = value.number - (value.completedNumber - value.extraNumber)
				value.customExtraNumber = 0
			})
			res.data.rows = res.data.rows.sort((a, b) => a.customNormalNumber - b.customNormalNumber).reverse()
			return res.data
		})
	}
	handleChange(value) {
		console.log("handleChange", value);
		this.queryParam.bomName = value;
	}
	async seachFn(value) {
		this.fetching = true;
		if (!value) {
			return [];
		}
		this.bomData = [];
		let bom = await bompage({
			bomName: value,
			bomTypeList: [1, 2],
			pageNo: 1,
			pageSize: -1,
		});
		console.log(bom.data.rows);

		// let bom2 = await bompage({
		// 	bomName: value,
		// 	bomType: 2,
		// 	pageNo: 1,
		// 	pageSize: -1,
		// })
		this.fetching = false;
		return bom.data.rows;
	}
	async handleSearch(value) {
		console.log("handleSearch", value);
		let result = await this.seachFn(value);
		this.bomData = result.map(val => val.bomName);
	}
	handleExport() {
		let emsOrder = this.emsOrder
		let $data = this.table.$data
		$data = $data.localDataSource

		// let filterData = $data.filter(value => value.customNormalNumber > 0 || value.customExtraNumber > 0)
		let orderMaterialFullResultList = $data.map(value => {
			console.log(value);
			return Object.assign({}, value, {
				sourceOrderId: emsOrder.orderId,
				sourceOrderMaterialId: value.orderMaterialId,
				// number: value.customNormalNumber,
				extraNumber: value.customExtraNumber,
			})
		})
		console.log("orderMaterialFullResultList", orderMaterialFullResultList);
		console.log("$data", $data);

		let orderBean = {
			orderId: '',
			sourceOrderId: emsOrder.orderId,
			orderParentId: '',
			orderPids: '',
			orderNumber: '',
			orderType: this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id,
			orgId: '',
			targetOrgId: '',
			isOverseasStore: '',
			countryCode: '',
			file: '',
			remark: '',
			executeStatus: '',
			executeProgress: '',
			issueTime: '',
			estimateCompletionTime: '',
			receiveTime: '',
			status: '',
			createTime: '',
			createUser: '',
			updateTime: '',
			updateUser: '',
			orderMaterialFullResultList: orderMaterialFullResultList,
		}
		this.dwnLoading = true
		Vue.prototype.download("/emsOrderMaterial/scckExport", orderBean, `领料单_${Vue.prototype.dayjs(new Date()).format('YYYY/MM/DD HH:mm:ss')}.xls`, null, true).then(res => {
			this.dwnLoading = false
		})
	}
	//获取领用方
	getTeamList() {
		teamPage({
			pageSize: -1,
			status: 0
		}).then(res => {
			this.teamList = res.data.rows;
		})
	}
	show(record) {
		this.visible = true
		this.emsOrder = record
		this.title = `出库（${record.orderNumber}）`
		setTimeout(() => {
			this.handleOk()
		}, 100)
	}

	handleOk() {
		this.table.refresh()
	}


	handleSubmit() {
		console.log('111', this.emsOrder)
		let emsOrder = this.emsOrder
		let $data = this.table.$data
		$data = $data.localDataSource

		let filterData = $data.filter(value => value.customNormalNumber > 0 || value.customExtraNumber > 0)
		if (filterData.length == 0) {
			this.$message.error('请先填写物料的数量')
			return
		}

		this.$confirm({
			title: '系统提示',
			content: '是否确认出库？',
			onOk: () => {
				console.log(filterData);

				let orderMaterials = filterData.map(value => {
					console.log(value);
					return Object.assign({}, value, {
						sourceOrderId: emsOrder.orderId,
						sourceOrderMaterialId: value.orderMaterialId,
						number: value.customNormalNumber,
						extraNumber: value.customExtraNumber,
					})
				})
				let orderBean = {
					orderId: '',
					sourceOrderId: emsOrder.orderId,
					orderParentId: '',
					orderPids: '',
					orderNumber: '',
					orderType: this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id,
					orgId: '',
					targetOrgId: '',
					isOverseasStore: '',
					countryCode: '',
					file: '',
					remark: '',
					executeStatus: '',
					executeProgress: '',
					issueTime: '',
					estimateCompletionTime: '',
					receiveTime: '',
					status: '',
					createTime: '',
					createUser: '',
					updateTime: '',
					updateUser: '',
					orderMaterials: orderMaterials,
				}
				console.log(orderBean);
				addOutOrderForProductionOrder(orderBean).then(res => {
					//@ts-ignore
					if (res.success) {
						this.$message.info('出库成功')
						this.$emit("ok");
						this.handleCancel()
					} else {
						//@ts-ignore
						this.$message.error('出库失败：' + res.message)
					}
				})

			},
			onCancel() {
				console.log('Cancel');
			},
		});

	}

	handleCancel() {
		this.visible = false
	}


}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
